package com.ewhale.feitengguest.ui.shop.task

import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.RelativeSizeSpan
import androidx.core.content.ContextCompat
import com.ewhale.feitengguest.R
import com.ewhale.feitengguest.dto.ShopWalletDto
import com.ewhale.feitengguest.presenter.shop.task.IncreasePayPresenter
import com.ewhale.feitengguest.utils.pay.*
import com.ewhale.feitengguest.view.shop.task.IncreasePayView
import com.simga.library.activity.MBaseActivity
import com.simga.library.http.JsonUtil
import com.tencent.mm.sdk.openapi.IWXAPI
import com.tencent.mm.sdk.openapi.WXAPIFactory
import kotlinx.android.synthetic.main.pay_task.*
import java.math.BigDecimal

class IncreasePayActivity : MBaseActivity<IncreasePayPresenter>(), IncreasePayView, PayCallBack, WeiXinPayCallBack {
    private var payType = 2 //2支付宝1微信
    private var payUtils: PayUtils? = null
    private var api: IWXAPI? = null
    private var receiver: WeiXinPayReceiver? = null

    private var price: String? = null
    private var unitPrice = ""
    private var type: Int? = null
    private var number = 0
    private var missionId: Long? = null

    override fun onGetBundle(bundle: Bundle?) {
        super.onGetBundle(bundle)
        type = bundle!!.getInt("type")
        missionId = bundle.getLong("missionId")
        price = bundle.getString("price")
        if(type == INCREASE_NUMBER){
            number = bundle.getInt("number")
        }else{
            unitPrice = bundle.getString("unitPrice")!!
        }
    }

    override fun getViewId(): Int {
        return R.layout.pay_task
    }

    override fun isUseBaseTitleBar(): Boolean {
        return true
    }

    override fun init(savedInstanceState: Bundle?) {
        setTitle("收银台")
        tv_amount.text = BigDecimal(price).stripTrailingZeros().toPlainString()
        presenter.getShopWallet()
        //第三方支付配置
        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID)
        payUtils = PayUtils(this, this)
        receiver = WeiXinPayReceiver()
        receiver!!.setWeiXinPayCallBack(this)
        val filter = IntentFilter()
        filter.addAction(WeiXinPayReceiver.WEI_XI_PAY_CALLBACK)
        registerReceiver(receiver, filter)
    }

    override fun showWallet(shopWalletDto: ShopWalletDto) {
        var hint = "平台账户余额\n" + "余额：" + shopWalletDto.balance
        //当余额小于应付金额的时候
        val spannableString: SpannableString?
        if (shopWalletDto.balance.compareTo(BigDecimal(price)) == -1) {
            rb_wallet.isEnabled = false
            payType = 2
            rb_alipay.isChecked = true
            hint = "$hint    余额不足"
            spannableString = SpannableString(hint)
            val colorSpan1 = ForegroundColorSpan(ContextCompat.getColor(mContext, R.color.main_color))
            spannableString.setSpan(colorSpan1,
                    6, hint.length - 4,
                    Spanned.SPAN_INCLUSIVE_EXCLUSIVE)

            val colorSpan2 = ForegroundColorSpan(ContextCompat.getColor(mContext, R.color.text_999999))
            spannableString.setSpan(colorSpan2,
                    hint.length - 4, hint.length,
                    Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
        } else {
            payType = 3
            rb_wallet.isChecked = true
            spannableString = SpannableString(hint)
            val colorSpan = ForegroundColorSpan(ContextCompat.getColor(mContext, R.color.main_color))
            spannableString.setSpan(colorSpan,
                    6, hint.length,
                    Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
        }
        spannableString.setSpan(RelativeSizeSpan(0.8f), 6, hint.length, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
        rb_wallet.text = spannableString
    }

    override fun initListener() {
        super.initListener()
        radioGroup.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                R.id.rb_alipay -> {
                    payType = 2
                }
                R.id.rb_wechat -> {
                    payType = 1
                }
                R.id.rb_wallet -> {
                    payType = 3
                }
            }
        }
        btn_commit.setOnClickListener {
            if (payType == 1) {
                if (!isWXAppInstalledAndSupported()) {
                    showToast("您未安装微信")
                    return@setOnClickListener
                }
            }
            if (payType == 3) {
                presenter.payTaskByWallet(type!!,number,unitPrice,missionId!!)
            } else {
                presenter.payTaskByThird(payType,type!!,number,unitPrice,missionId!!)
            }
        }
    }
    override fun paySuccess() {
        showToast("支付成功")
        sendBroadcast(Intent("UPDATE_TASK_LIST"))
        sendBroadcast(Intent("UPDATE_TASK_DETAIL"))
        finish()
    }

    override fun goToThirdPay(info: Any) {
        if(payType == 1){
            val weixinDto = JsonUtil.fromJson(info.toString(),PayWeixinDto::class.java)
            payUtils!!.payByWXPay(weixinDto)
        }else{
            payUtils!!.payByAliPay(info.toString())
        }
    }

    override fun onPaySuccess(payType: PayType?) {
        showToast("支付成功")
        sendBroadcast(Intent("UPDATE_TASK_LIST"))
        sendBroadcast(Intent("UPDATE_TASK_DETAIL"))
        finish()
    }

    override fun onPayFail(payType: PayType?) {
        showToast("支付失败")
    }

    override fun onPayCancel(payType: PayType?) {
        showToast("支付取消")
    }

    override fun onWXPay(code: String?) {
        PayCallBackEvent(PayType.WXPAY, code).payAction(this)
    }

    /**
     * 判断是否已经安装微信
     *
     * @return (true.已安装 false.未安装)
     */
    private fun isWXAppInstalledAndSupported(): Boolean {
        val msgApi = WXAPIFactory.createWXAPI(this, null)
        msgApi.registerApp(Constants.APP_ID)
        return msgApi.isWXAppInstalled && msgApi.isWXAppSupportAPI
    }

    override fun onDestroy() {
        super.onDestroy()
        if (receiver != null) {
            unregisterReceiver(receiver)
        }
    }

    override fun showProLoading() {
        showLoading()
    }

    override fun dimissProLoading() {
        dismissLoading()
    }

    override fun showErrorMessage(postCode: Int, code: String?, message: String?) {
        showErrorMsg(code, message)
    }

    companion object {
        const val INCREASE_PRICE = 1001
        const val INCREASE_NUMBER = 1002
        fun open(mContext: MBaseActivity<*>, missionId:Long,price: String, unitPrice: String, type: Int) {
            val bundle = Bundle()
            bundle.putString("price", price)
            bundle.putString("unitPrice", unitPrice)
            bundle.putInt("type", type)
            bundle.putLong("missionId", missionId)
            mContext.startActivity(bundle,  IncreasePayActivity::class.java)
        }
        fun open(mContext: MBaseActivity<*>, missionId:Long, price: String, number: Int, type: Int) {
            val bundle = Bundle()
            bundle.putString("price", price)
            bundle.putInt("number", number)
            bundle.putInt("type", type)
            bundle.putLong("missionId", missionId)
            mContext.startActivity(bundle,  IncreasePayActivity::class.java)
        }
    }
}
